import type { Module } from 'vuex'
import { ILoginState } from './types'
import { IRootState } from '../types'
import {
  loginAccountRequest,
  loginGetUserInfo,
  loginRoleMenuReequest
} from '@/servies/login/login'
import { localCache } from '@/cache'
import router from '@/router'
import { mapAllRouter, mapMenuToRoutes } from '@/utils/map-menus'
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state: () => {
    return {
      token: '',
      userInfo: {},
      userMenuInfo: {}
    }
  },
  getters: {},
  mutations: {
    loginAccountMutation(state, payload) {
      state.token = payload
    },
    userInfoMutation(state, payload) {
      state.userInfo = payload
    },
    userMenuInfoMutation(state, payload) {
      state.userMenuInfo = payload
      const routes = mapMenuToRoutes(payload)
      routes.forEach((route) => router.addRoute('main', route))
    }
  },
  actions: {
    async loginAccountAction({ commit, dispatch }, payload) {
      // 获取token
      const loginResult = await loginAccountRequest(payload)
      const { id, token } = loginResult.data
      commit('loginAccountMutation', token)
      localCache.setItem('token', token)
      // 获取用户信息
      const userInfoRequest = await loginGetUserInfo(id)
      const userInfo = userInfoRequest.data
      commit('userInfoMutation', userInfo)
      localCache.setItem('userInfo', userInfo)
      //根据角色获取菜单树
      const roleMenuResult = await loginRoleMenuReequest(userInfo.role.id)
      const userMenus = roleMenuResult.data
      commit('userMenuInfoMutation', userMenus)
      localCache.setItem('menuInfo', userMenus)
      router.push('/main')
    },
    loadLocalLogin({ commit, dispatch }) {
      const token = localCache.getItem('token')
      if (token) {
        commit('loginAccountMutation', token)
      }
      const userInfo = localCache.getItem('userInfo')
      if (userInfo) {
        commit('userInfoMutation', userInfo)
      }
      const userMenus = localCache.getItem('menuInfo')
      if (userMenus) {
        commit('userMenuInfoMutation', userMenus)
      }
    }
  }
}
export default loginModule
